const express = require('express')
const router = express.Router()


const LeaveWorld = require('../../models/LeaveWorld')

// 添加留言
router.post('/add', (req, res) => {
    new LeaveWorld(req.body).save().then(LeaveWorld => {
        res.json(LeaveWorld)
    })
})

//查询留言
router.get('/', (req, res) => {
    LeaveWorld.find()
        .then(LeaveWorld => {
            if (!LeaveWorld) {
                return res.status(404).json('没有任何内容')
            }
            res.json(LeaveWorld)
        })
        .catch(err => res.status(404).json(err))
})

// 删除留言
router.delete('/delete/:id', (req, res) => {
    LeaveWorld.findOneAndRemove({
        _id: req.params.id
    }).then(LeaveWorld => res.json(LeaveWorld))
        .catch(err => res.status(404).json('删除失败'))
})

//添加评论
router.post('/addComment/:id', (req, res) => {
    LeaveWorld.findOneAndUpdate({
        _id: req.params.id
    }, {
        $set: {
            comment: req.body.comment
        }
    }, {
        new: true
    }).then(leaveWorld => res.json(leaveWorld))
})

//删除评论
router.delete('/removeComment/:id/:comment', (req, res) => {
    LeaveWorld.update({
        _id: req.params.id
    }, {
        $pull: {
            comment: req.params.comment
        }
    }, err => {
        if (err) {
            console.log(err);
        }
    })
})
module.exports = router